import { messages, queryCurrencyPrecision } from "share/common";
import React from 'react'
import { connect } from "react-redux";
import { Tooltip, Spin, message } from 'antd'
import invoiceBagApproveService from 'containers/financial-management/invoice-bag-approve/invoice-bag-approve.service'
import NewExpense from 'containers/my-account/new-expense'
import SlideFrame from 'components/slide-frame'
import moment from "moment";
import baseService from 'share/base.service'
import { setDocumentaryCompany } from "actions/login";
import ResizeTable from 'components/resize-table'

class ExpenseList extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      data: {
        invoiceDTOs: [],
        freeReceiptStatistics: null,
        withoutReceiptBaseAmount: 0,
        needReceiptBaseAmount: 0,
        totalBaseAmount: 0,
        baseCurrency: ''
      },
      columns: [{
        dataIndex: 'index', title: messages('financial-management.key403')/*序号*/,
        render: (text, record, index) => index + 1, width: 50
      }, {
        dataIndex: 'businessCode', title: messages('financial-management.key737')/*报销单编号*/, width: 150,
        sorter: (a, b) => a.businessCode > b.businessCode || -1,
        render: text => <Tooltip title={text} placement='topLeft'>{text}</Tooltip>
      }, {
        dataIndex: 'expenseTypeName', title: messages('common.expense.type')/*费用类型*/, width: 100,
        sorter: (a, b) => a.expenseTypeName > b.expenseTypeName || -1,
        render: text => <div className='bad-table-cell' style={{ width: 84 }}>
          <Tooltip
            title={text} placement='topLeft'
            overlayStyle={{ maxWidth: 200,  whiteSpace: 'pre-wrap' }}
          >
            {text}
          </Tooltip>
        </div>
      }, {
        dataIndex: 'createdDate', title: messages('financial-management.key404')/*日期*/, width: 100,
        sorter: (a, b) => new Date(a.createdDate).getTime() - new Date(b.createdDate).getTime(),
        render: createdDate => {
          let text = createdDate ? moment(createdDate).format('YYYY-MM-DD') : '-';
          return <Tooltip title={text} placement='topLeft'>{text}</Tooltip>
        }
      }, {
        dataIndex: 'invoiceCurrencyCode', title: messages('financial-management.key405')/*币种*/, width: 100,
        sorter: (a, b) => a.invoiceCurrencyCode > b.invoiceCurrencyCode || -1
      }, {
        dataIndex: 'amount', title: messages('financial-management.key406')/*金额*/, width: 100,
        sorter: (a, b) => a.amount - b.amount,
        render: (value, record) => this.filterMoney(value, queryCurrencyPrecision(record.invoiceCurrencyCode))
      }, {
        dataIndex: 'actualCurrencyRate', title: messages('financial-management.key157')/*汇率*/, width: 100,
        render: text => <Tooltip title={text.toFixed(2)} placement='topLeft'>{text.toFixed(2)}</Tooltip>
      }, {
        dataIndex: 'baseAmount', title: messages('common.base.currency.amount')/*本位币金额*/, width: 100,
        render: baseAmount => this.filterMoney(baseAmount, queryCurrencyPrecision(''))
      }, {
        dataIndex: 'comment', title: messages('financial-management.key528')/*备注*/, width: 150,
        render: comment => <div className='bad-table-cell' style={{ width: 134 }}>
          <Tooltip
            title={comment || '-'}
            overlayStyle={{ maxWidth: 200,  whiteSpace: 'pre-wrap' }}
            placement='topLeft'
          >{comment || '-'}</Tooltip>
        </div>
      }, {
        dataIndex: 'owner', title: messages('financial-management.key738')/*费用归属人*/, width: 150,
        render: owner => <div className='bad-table-cell' style={{ width: 134 }}>
          <Tooltip
            title={owner.fullName}
            placement='topLeft'
            overlayStyle={{ maxWidth: 200,  whiteSpace: 'pre-wrap' }}
          >
            {owner.fullName}
          </Tooltip>
        </div>
      }, {
        dataIndex: 'attachments', title: messages('common.attachments')/*附件*/, width: 50
        ,render: attachments => attachments ? attachments.length : 0
      }, {
        dataIndex: 'invoiceOID', title: messages('financial-management.key254')/*操作*/, width: 50,
        render: (invoiceOID, record) => this.state.loadingExpense === invoiceOID ? <Spin/> : (
          <a onClick={() => this.handleClickExpense(record)}>{messages('common.view')/*查看*/}</a>
        )
      }],
      loading: false,
      nowExpense: {},
      loadingExpense: null,
      showExpenseDetail: false
    }
  }

  componentDidMount() {
    this.getList();
  }

  getList(){
    this.setState({ loading: true });
    invoiceBagApproveService.getExpenseListByBagId(this.props.invoiceBagId).then(res => {
      this.setState({ data: res.data, loading: false })
    })
  }

  handleClickExpense = record => {
    if(this.state.loadingExpense) {
      message.error(messages('financial-management.key750')/*请等待*/);
      return ;
    }
    this.setState({ loadingExpense: record.invoiceOID });
    baseService.getCompanyByUserOID(record.applicantOID).then(res => {
      this.props.dispatch(setDocumentaryCompany(res.data));
      this.setState({
        showExpenseDetail: true,
        nowExpense: record,
        loadingExpense: null
      });
    });
  };

  getAmount = (baseCurrency, data) => {
    if(!data)
      return `${baseCurrency} 0.00`;
    if(data.length === 0)
      return '0.00';
    else {
      let map = {};
      data.map(item => {
        Object.keys(item).map(key => {
          map[key] = item[key];
        })
      });
      return Object.keys(map)
        .map(c => `${c} ${this.filterMoney(map[c] / 100, queryCurrencyPrecision(c), true)}`)
        .join(' , ');
    }
  };

  renderExpandedRow = type => (
    <div
      className={`${
        type.level === 'WARN' ? 'warning-expanded-row' :
          (type.level === 'ERROR' ? 'error-expand-row' : '')
      }`}
    >
      <span>{type.name}</span>
      {type.toast && <span>:{type.toast}</span>}
    </div>
  );

  renderExpandedSpan = type => <span>{type.name}/</span>;

  renderAllExpandedRow = record => {
    let result = [];
    let infoRes = [];
    let types = record.invoiceLabels || [];
    let lastIndex = -1;
    types.map((label, index) => {
      if (label.level !== 'INFO') {
        result.push(this.renderExpandedRow(label, '', index));
      } else {
        lastIndex = label.name;
        infoRes.push(this.renderExpandedSpan(label, '', index));
      }
    });
    let infoLength = infoRes.length;
    infoLength > 0 && (infoRes[infoLength - 1] = <span key="lastIndex">{lastIndex}</span>);
    if(infoRes.length > 0)
      result.push(infoRes);
    return result.length > 0 ? result : null;
  };

  renderClass = record => {
    return record.invoiceLabels && record.invoiceLabels.length > 0 ? '' : 'row-expand-display-none'
  };

  editNowExpenseCallBack = expense => {
    return new Promise(resolve => {
      if (expense && expense.invoiceOID) {
        invoiceBagApproveService.getExpenseListByBagId(this.props.invoiceBagId).then(res => {
          this.setState({ data: res.data });
          resolve(expense);
        }).catch(() => {
          resolve(expense)
        })
      }
    })
  };

  getApportion = expense => {
    let result = [];
    if(expense && expense.expenseApportion) {
      expense.expenseApportion.map(field => {
        field.costCenterItems && field.costCenterItems.map(item => {
          if(item.apportionItem && !(
            result.find(r => r.costCenterOID === item.costCenterOID)
          )){
            result.push({
              fieldName: item.fieldName,
              costCenterOID: item.costCenterOID,
              costCenterItemName: item.costCenterItemName,
              name: item.fieldName,
              costCenterItemOID: item.costCenterItemOID,
              required: item.required
            });
          }
        });
      });
    }
    return result;
  };

  handleClose = flag => {
    this.setState({ showExpenseDetail: false, nowExpense: {} });
    if(flag === true) {
      this.getList();
    }
  };

  render() {
    const { loading, columns, data, nowExpense, showExpenseDetail } = this.state;
    const {
      invoiceDTOs, freeReceiptStatistics, withoutReceiptBaseAmount,
      needReceiptBaseAmount, totalBaseAmount, baseCurrency
    } = data;
    let expenseReportInvoices = invoiceDTOs.map(dto => {
      dto.invoiceView = JSON.parse(JSON.stringify(dto));
      return dto;
    });
    return (
      <div>
        <div className="table-count"> {messages('financial-management.key739')/*费用数量*/}：
          <b className="number">{invoiceDTOs.length}</b>
          <span className="ant-divider"/> {messages('financial-management.key740')/*需贴票总计*/}：{
            freeReceiptStatistics && Object.keys(freeReceiptStatistics).length > 1 ? (
              <b className="number">-</b>
            ) : (
              <b className="number">{baseCurrency}&nbsp;{this.filterMoney(needReceiptBaseAmount)}</b>
            )}
          <span className="ant-divider"/>
          {messages('financial-management.key741')/*金额总计*/}：
          <b className="number">{baseCurrency}&nbsp;{this.filterMoney(totalBaseAmount)}</b>
          &nbsp;&nbsp; ({messages('financial-management.key742')/*无票*/}：
          <b className="number">{baseCurrency}&nbsp;{this.filterMoney(withoutReceiptBaseAmount)}</b>
          &nbsp;&nbsp; {messages('common.invoice.free')/*免贴票*/}：
          <b className="number">{this.getAmount(baseCurrency, freeReceiptStatistics)}</b>
          )
        </div>
        <ResizeTable
          columns={columns}
          bordered
          rowKey="id"
          expandedRowRender={this.renderAllExpandedRow}
          rowClassName={this.renderClass}
          loading={loading}
          scroll={{ x: true }}
          pagination={false}
          dataSource={invoiceDTOs}
          size="middle"
        />
        <SlideFrame
          show={showExpenseDetail}
          content={NewExpense}
          title={messages('financial-management.key743')/*费用详情*/}
          hasFooter={false}
          width={800}
          params={{
            readOnly: true,
            audit: true,
            fromBag: true,
            isWaitForAudit: nowExpense.status === 1003,
            slideFrameShowFlag: showExpenseDetail,
            nowExpense,
            expenseReportInvoices,
            expenseReport: {
              ...nowExpense,
              companyOID: nowExpense.expCompanyOID,
              docCompanyOID: nowExpense.expDocCompanyOID,
              expenseReportInvoices
            },
            costCenterItemsApportion: this.getApportion(nowExpense),
            editNowExpenseCallBack: this.editNowExpenseCallBack,
            showExpenseReportInvoices: invoiceDTOs,
            switchingInvoice: index => this.handleClickExpense(invoiceDTOs[index])
          }}
          afterClose={this.handleClose}
          onClose={() => this.setState({ showExpenseDetail: false, nowExpense: {} })}
        />
      </div>
    )
  }
}

function mapStateToProps() {
  return {}
}

export default connect(mapStateToProps)(ExpenseList)
